var appPath = getAppPath();
var uploader = null;

$(function(){
	initJspGrid();
});

// 图像缩放
//function DrawImage(ImgD,FitWidth,FitHeight){
//    var image=new Image();
//    image.src=ImgD.src;
//    if(image.width>0 && image.height>0){
//        if(image.width/image.height>= FitWidth/FitHeight){
//            if(image.width>FitWidth){
//                ImgD.width=FitWidth;
//                ImgD.height=(image.height*FitWidth)/image.width;
//            }else{
//                ImgD.width=image.width; 
//               ImgD.height=image.height;
//            }
//        } else{
//            if(image.height>FitHeight){
//                ImgD.height=FitHeight;
//                ImgD.width=(image.width*FitHeight)/image.height;
//            }else{
//                ImgD.width=image.width; 
//               ImgD.height=image.height;
//            } 
//       }
//    }
//}

// 字体列表初始化
function initJspGrid(){
	
	$('#fontGrid').datagrid({
	    url:appPath + "/itbFont/getFontList.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
		checkbox:false,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}/*,
	        {field:'op',title:'操作',width:30,align:'center',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		if(!rowData.img_id) return "";
	        		return "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
	        	}
	        }*/
	    ]],
	    columns:[[
	        /*{field:'thumb_s',title:'预览',width:100,align:'center',sortable:false,
	        	formatter:function(thumb_s, rowData, rowIndex){
	        		if(!rowData.thumb_s)return "";
	        		return '<img src="' + rowData.thumb_s + '" onload=javascript:DrawImage(this,160,40); style="height:120px">';
	        	}},*/
	        {field:'font_id',title:'字体ID',width:35,align:'left',sortable:false},
	        {field:'font_name',title:'字体名称',width:90,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.font_id) return "<span style='color:red'>N/A</span>";
	        		if(Number(rowData.publish||'0')==1) {
	        			return "<span style='color:red'>"+rowData.font_name+"</span>";
	        		}
	        		return "<a href='javascript:void(0)' onClick='showEditName("+rowData.font_id+",\""+rowData.font_name+"\")'>"+rowData.font_name+"</a>";
	        	}
	        },
	        {field:'file_name',title:'原文件名',width:100,align:'left',sortable:false},
	        {field:'url',title:'资源地址',width:240,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.url) return "<span style='color:red'>N/A</span>";
	        		return rowData.url.replace('http://itbour-back.oss-cn-hangzhou.aliyuncs.com','');
	        	}
	        },
	        {field:'publish',title:'发布状态',width:50,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.font_id) return "<span style='color:red'>N/A</span>";
	        		if(Number(value||'0')==1) {
	        			return "<span style='color:green'>已发布</span>";
	        		}
	        		return "<span style='color:blue'>未发布</span>";
	        	}
	        },
	        {field:'create_time',title:'创建时间',width:80,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:80,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加字体',
			iconCls:'icon-add',
			handler:function(){
				showAddInfo();
			}
		},
		{
			text:'发布字体',
			iconCls:'icon-ok',
			handler:function(){
				doPublish();
			}
		},
		{
			text:'删除字体',
			iconCls:'icon-cancel',
			handler:function(){
				delFont();
			}
		}]
	    
	});

}

/**
 * 展现添加字体窗口
 */
function showAddInfo(){
	$("#fontUploadTable").show();
	$('#fontUploadForm').form('clear');
	
	clearUploadList();
	
	$("#addDlgBtn").show();
	$('#addDlg').window({
		title:'添加字体文件',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#addDlg').window('move',{top:20,left:20});
	$('#addDlg').window('open');
	
	//initFileUploader();
	initOSS();
}

/**
 * 删除字体
 */
function delFont(){
	var selectItem=$("#fontGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择字体','warning');
		return;
	}
	
	var ids = "";
	var bOK = true;
	$.each(selectItem, function(index, item){
		ids = ids + item.font_id + ",";
		if(item.publish==1 || item.publish=='1') {
			bOK = false;
		}
	});
	
	if(!bOK) {
		return $.messager.alert('提示信息','不能删除已发布字体!','warning');
	}
	
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var url = appPath+"/itbFontWeb/deleteFont.action?delIds="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery();
				}
			});
        }
	});
}

//function initFileUploader() {
//
//	$("#fontFile").ajaxfileupload({
//		'action' : appPath+"/itbFont/fileAction.action", 
//		'valid_extensions' : ['ttf','TTF'],
//		'filename_item' : $("#fontFileName"),
//		'submit_button' : $("#postFont"),
//		'params': {
//	        'userId': $("#userId").val(),
//	        'itb_fontName':''
//	      },
//	      'onComplete': function(response) {
//	    	  if (response.status == true) {	    	  
//		    	  insertFontInfo(response.fileName, response.savePath);
//		    	  setMsg("green", "上传成功！")
//	    	  } else {
//	    		  setMsg("red", response.message)
//	    	  }
//	      },
//	      'onStart': function() {
//	    	  $('#uploadMsg').hide();
//	    	 // setMsg("green", "文件上传中...");
//	         // if(weWantedTo) return false; // cancels upload
//	      },
//	      'onCancel': function() {
//	    	  //
//	      }
//	    });
//}

$('#fontFile').change(function() {
	$('#uploadMsg').hide();
});

function setMsg(color, msg) {
	$('#msgTxt').css("color", color);
	$('#msgTxt').val(msg);
	$('#uploadMsg').show();
}

function insertFontInfo(fileName, fileNameNoExt ,urlpath) {
	var url = appPath+"/itbFontWeb/addFont.action"
	var sendData = {
		"fontInfo.font_name": fileNameNoExt || fileName,
		"fontInfo.file_name": fileName,
		"fontInfo.update_by": g_userId || 'Unknown',
		"fontInfo.url": urlpath,
		"fontInfo.thumb_s": ''// TODO
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			doQuery();
        }  
    });
}

function doPostData() {
	//
}

/**
 * 关闭对话框
 */
function cancelPostData(){
	$('#addDlg').window('close');
}

/**
 * 显示字体名称编辑窗口
 */
function showEditName(fontId, fontName){
	$("#fontId").val(fontId);
	$("#fname").val(fontName);
	
	$("#nameBtn").show();
	$('#nameDlg').window({
		title:'字体名称设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#nameDlg').window('move',{top:20,left:20});
	$('#nameDlg').window('open');
}
/**
 * 修改字体名称
 */
function doUpdName(){// TODO
	var fontId = $("#fontId").val();
	var fname = $("#fname").val();
	if(!fname || fname.length == 0){
		$.messager.alert('提示信息','请输入字体名称！','warning');
		return;
	}else if(fname && fname.length > 50){
		$.messager.alert('提示信息','请控制在50个字符以内！','warning');
		return;
	}
	
	// 检查
	var url = appPath+"/itbFontWeb/chkFontName.action";
	var sendData = {
			"fontInfo.font_name": fname,
		};
	$.post(url,sendData,function(data){
		if(data=="ok"){
			// 更新
			var url2 = appPath+"/itbFontWeb/updFont.action";
			var sendData2 = {
					"fontInfo.font_name": fname,
					"fontInfo.font_id": fontId
				};
			$.post(url2,sendData2,function(data2){
				if(data2=="ok"){
					$.messager.alert('提示信息','［字体名称］已更新！','info',function(){
						doQuery();
						$('#nameDlg').window('close');
					});
				}else {
					$.messager.alert('提示信息','［字体名称］更新失败！','warning');
				}
			});
		}else {
			$.messager.alert('提示信息','<span style="color:red">已存在同名字体！</span>','warning');
		}
	});
}

/**
 * 取消字体名称编辑
 */
function cancelUpdName(){
	$('#nameDlg').window('close');
}

/**
 * 发布字体
 */
function doPublish(){
	var selectTmpl=$("#fontGrid").datagrid("getChecked");
	if(!selectTmpl || selectTmpl.length == 0){
		$.messager.alert('提示信息','请选择字体！','warning');
		return;
	}else if(selectTmpl.length>1){
		$.messager.alert('提示信息','请选择单个字体进行处理！','warning');
		return;
	}
	
	var id = "";
	var doFlg = false;
	$.each(selectTmpl, function(index, item){
		if(item.publish != 1 && item.publish != '1'){
			doFlg = true;
			id=item.font_id;
			return false;
		}
	});
	
	if(!doFlg){
		$.messager.alert('提示信息','请选择未发布字体进行处理！','warning');
		return;
	}
	
	$.messager.confirm("确认",
		"是否确认发布字体？<br/><span style='color:red'>＊请仔细核对［字体名称］，发布后不能再修改！</span>",
		function (r) {
	        if (r) {
	        	// 检查
	        	var url = appPath+"/itbFontWeb/chkFontName.action";
	        	var sendData = {
	        			"fontInfo.font_id": id,
	        			"fontInfo.publish": 1
	        		};
	        	$.post(url,sendData,function(data){
	        		if(data=="ok"){
	        			// 发布
	        			var url2 = appPath+"/itbFontWeb/updFont.action";
	    	        	$.post(url2,sendData,function(data2){
	    	        		if(data2=="ok"){
	    	        			$.messager.alert('提示信息','字体已发布！','info',function(){
	    	        				doQuery();
	    	        			});
	    	        		}else {
	    	        			$.messager.alert('提示信息','字体发布失败！','warning');
	    	        		}
	    	        	});
	        		} else {
	        			$.messager.alert('提示信息',"<span style='color:red'>［字体名称］与已发布字体有重名！</span>",'warning');
	        		}
	        	});
	        }
		}
	);
}

/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	var findUserId = $("#queryUserId").val();
	var findFontName=$("#queryFontName").val();
	var findFileName=$("#queryFileName").val();
	var findPubFlg = $("#queryPublish").combobox('getValue');
	if(findUserId&&findUserId.length>0) queryObject.findUserId = findUserId;
	if(findFontName&&findFontName.length>0) queryObject.findFontName = findFontName;
	if(findFileName&&findFileName.length>0) queryObject.findFileName = findFileName;
	if(findPubFlg&&findPubFlg.length>0) queryObject.findPubFlg = findPubFlg;
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#fontGrid").datagrid('unselectAll');
	$("#fontGrid").datagrid('load', getQueryParam());
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}

function isFont(url) {
    var res, suffix = "";
    var fontSuffixes = ["ttf"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = fontSuffixes.length; i < l; i++) {
        if (suffix === fontSuffixes[i]) {
            return true;
        }
    }
    return false;
}

//############### FOR OSS UPLOAD START ###############
var g_object_name = '';
var dtNow = Date.parse(new Date())/1000;

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
  }
	return str;
}

function getSuffix(filename) {
  var pos = filename.lastIndexOf('.');
  var suffix = '';
  if (pos != -1) {
      suffix = filename.substring(pos);
  }
  return suffix;
}

function calculate_object_name(filename) {
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
  g_object_name = "font/U"+g_userId+"/"+nowStr + randomString(20);
}

function set_upload_param(up, filename, ret) {
  
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date())/1000;
	OSS_PARAM.flg = false;
  if (OSS_PARAM.expire/1000 < dtNow + 5) {// 5s
  	var url = appPath+"/itbFont/getOSSToken.action"
      $.get(url, function(data){  
  		if (data && data.signature) { 
  			OSS_PARAM.expire = data.expire;
  			OSS_PARAM.uploadHost = data.uploadHost;
  			OSS_PARAM.accessKeyId = data.accessKeyId;
  			OSS_PARAM.policyBase64 = data.policyBase64;
  			OSS_PARAM.signature = data.signature;
  			OSS_PARAM.flg = true;
  			
  			doUpStart(up, filename, ret);
          } else {
          	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
          }  
      });
  } else {
  	doUpStart(up, filename, ret);
  }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
		calculate_object_name(filename);
	}
	var new_multipart_params = {
		'key' : g_object_name,
		'policy': OSS_PARAM.policyBase64,
		'OSSAccessKeyId': OSS_PARAM.accessKeyId,
		'success_action_status' : '200', //让服务端返回200,不然默认会返回204
		'signature': OSS_PARAM.signature,
	};

	up.setOption({
		'url': OSS_PARAM.uploadHost,
		'multipart_params': new_multipart_params
	});

	up.start();
}

function clearUploadList() {
	$(".upload_progress_bar").remove();
	$(".upload_progress").remove();
	$(".upload_file_info").remove();
}

function initOSS() {
	if (uploader) {
		return;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selFiles', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',

		init: {
			PostInit: function() {
				document.getElementById('postFiles').onclick = function() {
		            set_upload_param(uploader, '', false);
		            return false;
				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bAllOk = true;
				plupload.each(files, function(file) {
					if (isFont(file.name)) {
						// add file info list
						document.getElementById('ossfile').innerHTML += 
	                    	'<div id="' + file.id + '" class="upload_file_info">'
	                    	+ file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>'
	                    	+ '<div class="upload_progress">'
	                    	+ '<div class="upload_progress_bar" style="width: 0%">'
	                    	+ '</div></div></div>';
					} else {
						bAllOk = false;
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					}
				});
				
				if (!bAllOk) {
					setMsg("red", "已过滤非字体文件！");
				}
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0];
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
				
				setMsg("green", file.name + ' 上传中...');
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功:' + g_object_name;
	            	
	            	var pos = file.name.lastIndexOf(".");
	                var fileNameNoExt = file.name.substring(0, pos);
	            	insertFontInfo(file.name, fileNameNoExt, OSS_PARAM.uploadHost+'/'+ g_object_name);
	            	setMsg("green", '上传成功!');
	            }
	            else {
	            	setMsg("red", '上传出错！');
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
	            }
			},

			Error: function(up, err) {
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}
//############### FOR OSS UPLOAD END ###############